package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "RoleFilter",urlPatterns = {"/*"})
public class RoleFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //实现请求对象，响应对象的强制类型转换
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //获取用户请求
        String uri = req.getRequestURI();
        if(uri.contains("login")){
            chain.doFilter(request, response);
        }else{
            HttpSession session = req.getSession();
            Object user = session.getAttribute("userInfo");
            if(user == null){
                resp.sendRedirect("./login.jsp");
            }else{
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}